package com.example.sso.server.controller;

import com.example.sso.server.entity.User;
import com.example.sso.server.repository.TokenRepository;
import com.example.sso.server.repository.UserRepository;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserInfoController {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private TokenRepository tokenRepository;
    
    private final Gson gson = new Gson();

    @PostMapping(value = "/oauth/api", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getUserInfo(
            @RequestParam("client_id") String clientId,
            @RequestParam("token") String accessToken,
            @RequestParam("method") String method) {
        
        // 验证令牌
        if (!tokenRepository.isValidToken(accessToken)) {
            return buildErrorResponse("access_denied", "无法识别的票据或票据已过期");
        }
        
        // 验证方法
        if (!"user_info".equals(method)) {
            return buildErrorResponse("invalid_request", "不支持的方法");
        }
        
        // 获取用户信息（这里简化处理，实际应该从令牌关联到用户）
        User user = userRepository.findByUsername("test"); // 实际应用中应从令牌获取用户
        
        // 返回用户信息
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        data.put("DataAction", 1);
        data.put("AccessID", 1);
        data.put("AccessType", 1);
        data.put("LastModify", System.currentTimeMillis());
        data.put("MappingName", null);
        data.put("MappingData", null);
        data.put("UserName", user.getUsername());
        data.put("NickName", null);
        data.put("RealName", user.getRealName());
        data.put("Mobile", null);
        data.put("Email", user.getEmail());
        data.put("Gender", null);
        data.put("Avatar", null);
        
        response.put("data", data);
        return gson.toJson(response);
    }
    
    private String buildErrorResponse(String error, String errorDescription) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("error", error);
        if (errorDescription != null) {
            errorResponse.put("error_description", errorDescription);
        }
        return gson.toJson(errorResponse);
    }
}
    